package ran.service.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import ran.constants.Constants;
import ran.constants.HttpConstants;
import ran.constants.UserIdentity;
import ran.domain.sysuser.entity.SysUser;
import ran.entity.LoginUser;
import ran.entity.Result;
import ran.domain.sysuser.dto.SysUserSaveDTO;
import ran.enums.ResultCode;
import ran.exception.ServiceException;
import ran.mapper.sysuser.SysUserMapper;
import ran.service.sysuser.ISysUserService;
import ran.service.TokenService;
import ran.utils.BCryptUtils;
import ran.utils.ThreadLocalUtil;
import ran.vo.LoginUserVO;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-10-03
 * Time: 14:42
 */
@Slf4j
@Service
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TokenService tokenService;
    @Value("${jwt.secret}")
    private String secret;
    @Override
    public Result<String> login(String userAccount, String password) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(SysUser::getPassword,SysUser::getUserId,SysUser::getNickName)
                .eq(SysUser::getUserAccount,userAccount);
        SysUser sysUser = sysUserMapper.selectOne(lambdaQueryWrapper);
        if (sysUser == null) {

            return Result.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if (BCryptUtils.matchesPassword(password,sysUser.getPassword())) {
            // 1.登录成功,调用tokenService, 生成token, 发送给客户端
            // 2.后续所有请求,先要通过token来身份认证
            // 3.用户使用中,适时延长jwt过期时间
            // 管理员没有头像, 这里传一个null
            return Result.ok(tokenService.createToken(sysUser.getUserId(),secret, UserIdentity.ADMIN.getValue(),sysUser.getNickName(),null));
        }
        log.info("管理员登录, sysUser:{}",sysUser);
        // 密码错误
        return Result.fail(ResultCode.FAILED_LOGIN);
    }


    @Override
    public boolean logout(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return tokenService.deleteLoginUser(ThreadLocalUtil.get(Constants.USER_KEY,String.class));
    }

    @Override
    public Result<LoginUserVO> info(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(ThreadLocalUtil.get(Constants.USER_KEY,String.class));
        if (loginUser == null) {
            return Result.fail();
        }
        log.info("获取登录用户信息, loginUser:{}",loginUser);
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return Result.ok(loginUserVO);
    }

    @Override
    public int add(SysUserSaveDTO sysUserSaveDTO) {
        List<SysUser> userList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));
        if (CollectionUtil.isNotEmpty(userList)) {
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
        return sysUserMapper.insert(sysUser);
    }




}
